package com.hanserwei.han_picture.websocket;

import com.hanserwei.han_picture.websocket.message.AiProcessMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * WebSocket消息服务
 *
 * @author hanserwei
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WebSocketMessageService {

    private final AiProcessWebSocketHandler webSocketHandler;

    private static void logDebug(Long userId) {
        log.debug("用户 {} 不在线，跳过WebSocket通知", userId);
    }

    /**
     * 通知AI处理开始
     */
    public void notifyAiProcessStart(Long userId, Long pictureId) {
        if (!webSocketHandler.isUserOnline(userId)) {
            logDebug(userId);
            return;
        }

        AiProcessMessage message = AiProcessMessage.createStartMessage(pictureId, userId);
        webSocketHandler.sendAiProcessMessage(userId, message);
        log.info("已通知用户 {} AI处理开始，图片ID: {}", userId, pictureId);
    }

    /**
     * 通知AI处理成功
     */
    public void notifyAiProcessSuccess(Long userId, Long pictureId, String aiTitle, String aiCategory, List<String> aiTags) {
        if (!webSocketHandler.isUserOnline(userId)) {
            logDebug(userId);
            return;
        }

        AiProcessMessage message = AiProcessMessage.createSuccessMessage(pictureId, userId, aiTitle, aiCategory, aiTags);
        webSocketHandler.sendAiProcessMessage(userId, message);
        log.info("已通知用户 {} AI处理成功，图片ID: {}, 标题: {}, 分类: {}, 标签: {}",
                userId, pictureId, aiTitle, aiCategory, aiTags);
    }

    /**
     * 通知AI处理失败
     */
    public void notifyAiProcessError(Long userId, Long pictureId, String error) {
        if (!webSocketHandler.isUserOnline(userId)) {
            logDebug(userId);
            return;
        }

        AiProcessMessage message = AiProcessMessage.createErrorMessage(pictureId, userId, error);
        webSocketHandler.sendAiProcessMessage(userId, message);
        log.info("已通知用户 {} AI处理失败，图片ID: {}, 错误: {}", userId, pictureId, error);
    }

    /**
     * 获取当前WebSocket连接数
     */
    public int getConnectionCount() {
        return webSocketHandler.getConnectionCount();
    }

    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(Long userId) {
        return webSocketHandler.isUserOnline(userId);
    }
}
